package drds.global_transaction.test.common;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ApplicationKeeper
{
	private final ReentrantLock lock = new ReentrantLock();
	private final Condition stopCondition = lock.newCondition();

	public ApplicationKeeper(ApplicationContext applicationContext)
	{
		addShutdownHook((AbstractApplicationContext) applicationContext);
	}

	private void addShutdownHook(final AbstractApplicationContext applicationContext)
	{
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					applicationContext.close();
					log.info("ApplicationContext " + applicationContext + " is closed.");
				} catch (Exception e)
				{
					log.error("failed to close ApplicationContext", e);
				}

				try
				{
					lock.lock();
					stopCondition.signal();
				} finally
				{
					lock.unlock();
				}
			}
		}));
	}

	public void keep()
	{
		synchronized (lock)
		{
			try
			{
				log.info("Application is keep running ... ");
				lock.wait();
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
}
